<template>
  <div>
    <!-- 右边基本表格 -->
    <BasicTable @register="registerTable">
      <!-- 表格标题 -->
      <template #tableTitle>
        <Icon :icon="getTitle.icon" class="m-1 pr-1" />
        <span> {{ title }} </span>
      </template>
      <!-- 表格右上角自定义按钮（新增...） -->
      <template #toolbar>
        <div v-for="(item, index) in butData" :key="index">
          <a-popconfirm
            v-if="item.btnKey === 'btnStatus'"
            title="是否确认价格生效？"
            ok-text="是"
            cancel-text="否"
            placement="bottom"
            @confirm="handleStatus()"
          >
            <a-button :key="index" :type="item.type" v-auth="item.auth">
              <Icon :icon="item.icon" /> {{ t(item.title) }}
            </a-button>
          </a-popconfirm>
          <a-button v-else :key="index" :type="item.type" @click="item.do" v-auth="item.auth">
            <Icon :icon="item.icon" /> {{ t(item.title) }}
          </a-button>
        </div>
      </template>
      <!-- 表格插槽 -->
      <template #firstColumn="{ record }">
        <a @click="handleForm({ cusCode: record.cusCode, invCode: record.invCode })">
          {{ record.cusCode }}
        </a>
      </template>
    </BasicTable>
    <!-- 页签方式编辑 -->
    <InputFormTabs @register="registerDrawer2" @success="handleSuccess" />
    <FormImport @register="registerImportModal" @success="handleSuccess" />
  </div>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsSettingPriceWecharCusInvPriceRouteList',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, onMounted, ref, watch } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { customListData, listSet } from '/@/api/test/testData';
  import { schemasData, tabConfigData } from '/@/utils/custom';
  import { useGlobSetting } from '/@/hooks/setting';
  import { downloadByUrl } from '/@/utils/file/download';
  import { BasicTable, BasicColumn, useTable, ActionItem } from '/@/components/Table';
  import { useDrawer } from '/@/components/Drawer';
  import { FormProps } from '/@/components/Form';
  import { useModal } from '/@/components/Modal';
  import InputFormTabs from './formTabs.vue';
  import FormImport from './formImport.vue';
  import {
    wecharCusInvPriceRouteDelete,
  } from '/@/api/setting/price/wecharCusInvPriceRoute';

  const { t } = useI18n('setting.price.wecharCusInvPriceRoute');
  const { showMessage } = useMessage();
  const emit = defineEmits(['success', 'register']);
  const props = defineProps({
    treeCode: String,
    invCode: String,
  });

  watch(
    [() => props.treeCode,() => props.invCode],
    async () => {
      await getForm().setFieldsValue({
        endCusCode: props.treeCode,
        invCode:props.invCode
      });
      reload();
    },
  );
  // watch(
  //   () => props.invCode,
  //   async () => {
  //     await getForm().setFieldsValue({
  //       endCusCode: props.treeCode,
  //       invCode:props.invCode
  //     });
  //     reload();
  //   },
  // );

  //配置表单内容
  const searchForm = ref<FormProps>({
    baseColProps: { lg: 12, md: 8 }, // 表单栅格布局
    labelWidth: 90, // 表单标签宽度
    schemas: [],
  });
  let tableColumns = ref<any>([]);
  let butData = ref<any>([]);
  let actionColumnData = ref<ActionItem[]>([]);
  let layVoucherView = ref<any>({});
  let listTabConfig = ref<any>({});
  const getTitle = ref({
    // 表格标题图标
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    value: listTabConfig.value.title,
  });
  let title = ref('');
  const actionColumn: BasicColumn = {
    width: 160,
    actions: (record: Recordable) => [
      {
        icon: 'clarity:note-edit-line',
        title: t('编辑价格及协同路线'),
        onClick: handleForm.bind(this, {
          endCusCode: record.endCusCode,
          cusCode: record.cusCode,
          invCode: record.invCode,
        }),
        auth: 'setting:price:edit',
      },
      {
        icon: 'ant-design:delete-outlined',
        color: 'error',
        title: t('删除价格及协同路线'),
        popConfirm: {
          title: t('是否确认删除价格及协同路线'),
          confirm: handleDelete.bind(this, {
            endCusCode: record.endCusCode,
            cusCode: record.cusCode,
            invCode: record.invCode,
          }),
        },
        auth: 'setting:price:edit',
      },
    ],
  };
  onMounted(async () => {
    const res = await listSet({ viewCode: 'bus001_cusPrice_list001' });
    title.value = res.layVoucherView.name;
    layVoucherView.value = res.layVoucherView;

    searchForm.value.schemas = schemasData(layVoucherView.value.listQuery.queryCols);

    tableColumns.value = layVoucherView.value.flistTabCols; //表格表头

    butData.value = layVoucherView.value.headBtns; //表格右上角按钮
    butData.value.forEach((item) => {
      if (item.btnKey == 'btnAdd') {
        item.do = () => handleForm({});
      } else if (item.btnKey == 'btnExport') {
        item.do = () => handleExport();
      } else if (item.btnKey == 'btnImport') {
        item.do = () => handleImport();
      } else if (item.btnKey == 'btnStatus') {
        item.do = () => handleStatus();
      }
    });

    actionColumnData.value = layVoucherView.value.rowBtns; //表格行内按钮

    listTabConfig.value = tabConfigData(res.layVoucherView.listTabConfig);
    setProps({
      api: customListData,
      beforeFetch: (params) => {
        params.url = listTabConfig.value.api;
        return params;
      },
      autoCreateKey: listTabConfig.value.autoCreateKey,
      bordered: listTabConfig.value.bordered,
      canResize: listTabConfig.value.canResize,
      clearSelectOnPageChange: listTabConfig.value.clearSelectOnPageChange,
      clickToRowSelect: listTabConfig.value.clickToRowSelect,
      ellipsis: listTabConfig.value.ellipsis,
      emptyDataIsShowTable: listTabConfig.value.emptyDataIsShowTable,
      inset: listTabConfig.value.inset,
      isTreeTable: listTabConfig.value.isTreeTable,
      pagination: listTabConfig.value.pagination,
      showIndexColumn: listTabConfig.value.showIndexColumn,
      showSummary: listTabConfig.value.showSummary,
      showTableSetting: listTabConfig.value.showTableSetting,
      striped: listTabConfig.value.striped,
      useSearchForm: listTabConfig.value.useSearchForm,
      tableSetting: listTabConfig.value.tableSetting,
      titleHelpMessage: listTabConfig.value.titleHelpMessage,
      maxHeight: listTabConfig.value.maxHeight,
      resizeHeightOffset: listTabConfig.value.resizeHeightOffset,
    });
    if (!listTabConfig.value.immediate) {
      reload();
    }
  });

  const [registerDrawer2, { openDrawer: openDrawer2 }] = useDrawer();
  const [registerTable, { reload, getForm, setProps, getSelectRows }] = useTable({
    actionColumn: actionColumn,
    columns: tableColumns,
    formConfig: searchForm.value as FormProps,
    rowSelection: {
      type: 'checkbox',
    },
  });
  function handleForm(record: Recordable) {
    openDrawer2(true, record);
  }

  async function handleExport() {
    const { ctxAdminPath } = useGlobSetting();
    downloadByUrl({
      url: ctxAdminPath + '/setting/price/wecharCusInvPriceRoute/exportData',
      target: '_self',
    });
  }

  const [registerImportModal, { openModal: importModal }] = useModal();

  function handleImport() {
    importModal(true, {});
  }

  async function handleDelete(record: Recordable) {
    const res = await wecharCusInvPriceRouteDelete(record);
    showMessage(res.message);
    handleSuccess();
  }

  async function handleStatus() {
    // if (getSelectRows().length) {
    //   var selIds = ref('');
    //   getSelectRows().forEach((item) => {
    //     selIds.value += item.cusCode + '|' + item.invCode + ',';
    //   });
    //   const res = await updateStatus({ selIds: selIds.value });
    //   showMessage(res.message);
    //   handleSuccess();
    // } else {
    //   showMessage('请先选择一行数据！！');
    // }
  }
  function handleSuccess1() {
    reload();
  }
  defineExpose({
    handleSuccess1,
  })

  function handleSuccess() {
    reload();
    emit('success');
  }
</script>
<style>
  .jeesite-editable-cell__action {
    display: none;
  }

  .edit-cell-align-center {
    width: 100% !important;
  }
</style>
